package com.aifeng.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.aifeng.base.BaseFragment
import com.aifeng.base.loadCircleImage
import com.aifeng.common_ui.base.oneClick
import com.aifeng.common_ui.base.startActivityEx
import com.aifeng.common_ui.helper.*
import com.aifeng.hassan_food.R
import com.aifeng.hassan_food.WebActivity
import com.aifeng.hassan_food.mine.*
import com.aifeng.model.BaseUrl
import com.aifeng.oss.scaleImage
import com.aifeng.utils.DialogHelper.showQRcodeDialog
import com.aifeng.utils.bindLifeCycle
import com.aifeng.utils.subscribeByNoError
import com.aifeng.viewmodel.LoginViewModel
import kotlinx.android.synthetic.main.fragment_main_five.*
import org.jetbrains.anko.sdk25.listeners.onClick
import org.json.JSONObject
import org.koin.androidx.viewmodel.ext.android.getViewModel

class MainFiveFragment : BaseFragment() {

    //调用这个方法切换时不会释放掉Fragment
    override fun setMenuVisibility(menuVisible: Boolean) {
        super.setMenuVisibility(menuVisible)
        this.view?.visibility = if (menuVisible) View.VISIBLE else View.GONE
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? = inflater.inflate(R.layout.fragment_main_five, container, false)

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initTitle()
    }

    override fun getViewModel() = getViewModel<LoginViewModel>()

    override fun onStart() {
        super.onStart()
        getData()
    }

    override fun initTitle() {
        five_head.oneClick { startActivityEx<InfoActivity>() }
        five_wallet.oneClick { startActivityEx<WalletActivity>() }
        five_all.oneClick { startActivityEx<OrderActivity>("index" to "1") }
        five_pay.oneClick { startActivityEx<OrderActivity>("index" to "2") }
        five_send.oneClick { startActivityEx<OrderActivity>("index" to "3") }
        five_get.oneClick { startActivityEx<OrderActivity>("index" to "4") }
        five_done.oneClick { startActivityEx<OrderActivity>("index" to "5") }
        five_reback.oneClick { startActivityEx<OrderRefundActivity>() }
        five_invite.oneClick { startActivityEx<ShareActivity>("index" to 0) }
        five_order.oneClick { startActivityEx<ShopActivity>() }
        five_addr.oneClick { startActivityEx<AddressActivity>() }
        five_service.onClick { startActivityEx<WebActivity>("title" to "在线客服") }
        five_setting.oneClick { startActivityEx<SettingActivity>() }

        five_house.oneClick {
            context?.showQRcodeDialog(
                hint = "使用微信扫描进入店铺即可下单",
                type = "url",
                url = getString("shopCode"),
                name = getString("shopName"),
                code = getString("shopId")
            )
        }

        five_register.oneClick {
            context?.showQRcodeDialog(
                hint = "扫描二维码，可快速注册账号",
                type = "qrcode",
                url = BaseUrl.registerCode + getString("shopId"),
                name = getString("shopName"),
                code = getString("shopId")
            )
        }

        five_code.oneClick {
            if (getString("shopId").isNotEmpty()) {
                context?.copyStringToClip(getString("shopId"))
                showToast("已复制邀请码到剪切板！")
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun getData(index: Int, isLoading: Boolean) {
        if (getIContext().isLogin) {
            getViewModel().userInfo(getString("userId"))
                .bindLifeCycle(getLifecycleOwner())
                .subscribeByNoError(
                    event = getViewModel(),
                    onSuccess = {
                        val user = JSONObject(it).optJSONObject("user") ?: JSONObject()
                        putShared("nickName", user.optNotNull("nick"))
                        putShared("shopName", user.optNotNull("shopname"))
                        putShared("shopCode", user.optNotNull("shopqrcode"))
                        putShared("headImg", user.optNotNull("headimg"))
                        putShared("balance", user.optNotNull("balance"))

                        putShared("realName", user.optNotNull("realname"))
                        putShared("bankCard", user.optNotNull("bankCardNumber"))
                        putShared("bindId", user.optNotNull("bind_wx_id"))
                        putShared("bindImg", user.optNotNull("bind_wx_img"))
                        putShared("bindName", user.optNotNull("bind_wx_nick"))

                        five_name.text = when {
                            getString("nickName").isNotEmpty() -> getString("nickName")
                            getString("realName").isNotEmpty() -> getString("realName")
                            else -> getString("phone")
                        }
                        five_code.text = "邀请码：${getString("shopId")}"

                        when {
                            five_img.getTag(R.id.empty_img) == null -> {
                                five_img.loadCircleImage(getString("headImg").scaleImage())
                                five_img.setTag(R.id.empty_img, getString("headImg"))
                            }
                            five_img.getTag(R.id.empty_img) != getString("headImg") -> {
                                five_img.loadCircleImage(getString("headImg").scaleImage())
                                five_img.setTag(R.id.empty_img, getString("headImg"))
                            }
                        }

                        val inviteNum = JSONObject(it).optNotEmpty("invite", "0").toNotInt()
                        val order = JSONObject(it).optJSONObject("order") ?: JSONObject()
                        val orderNum1 = order.optNotEmpty("state0", "0").toNotInt()
                        val orderNum2 = order.optNotEmpty("state1", "0").toNotInt()
                        val orderNum3 = order.optNotEmpty("state2", "0").toNotInt()

                        five_num1.apply {
                            text = orderNum1.toString()
                            visibility = if (orderNum1 > 0) View.VISIBLE else View.INVISIBLE
                        }
                        five_num2.apply {
                            text = orderNum2.toString()
                            visibility = if (orderNum2 > 0) View.VISIBLE else View.INVISIBLE
                        }
                        five_num3.apply {
                            text = orderNum3.toString()
                            visibility = if (orderNum3 > 0) View.VISIBLE else View.INVISIBLE
                        }
                        five_num4.apply {
                            text = inviteNum.toString()
                            visibility = if (inviteNum > 0) View.VISIBLE else View.INVISIBLE
                        }
                    }
                )
        }
    }

}
